/*
 * @Description: 数据源管理
 * @Author: seadon
 * @LastEditors: seadon
 * @Date: 2021-05-18 17:44:18
 * @LastEditTime: 2021-05-18 18:21:57
 */
import { ref, unref, ComputedRef, watch } from 'vue'
import { BasicTableProps } from '../types/table'

export function useDataSource(propsRef: ComputedRef<BasicTableProps>) {
	const dataSourceRef = ref<Recordable[]>([])

	watch(
		() => unref(propsRef).dataSource,
		() => {
			const { dataSource } = unref(propsRef)
			dataSource && (dataSourceRef.value = dataSource)
		},
		{
			immediate: true,
		}
	)

	async function updateTableData(index: number, key: string, value: any) {
		const record = dataSourceRef.value[index]
		if (record) {
			dataSourceRef.value[index][key] = value
		}
		return dataSourceRef.value[index]
	}

	return {
		dataSourceRef,
		updateTableData,
	}
}
